import os
import sys
import subprocess
import time

# 检查并安装依赖
def install_dependencies():
    print("正在检查和安装依赖...")
    try:
        # 安装requirements.txt中的依赖，并使用清华镜像源
        subprocess.check_call([
            sys.executable, "-m", "pip", "install", 
            "-i", "https://pypi.tuna.tsinghua.edu.cn/simple/",
            "-r", "requirements.txt"
        ])
        print("依赖安装成功！")
    except subprocess.CalledProcessError as e:
        print(f"依赖安装失败: {e}")
        print("请手动安装依赖后再启动服务。")

# 启动FastAPI服务
def start_server():
    try:
        print("正在启动Kitten TTS API服务...")
        print("服务将在 http://0.0.0.0:8000 运行")
        print("Swagger文档可访问: http://0.0.0.0:8000/docs")
        print("按 Ctrl+C 停止服务")
        
        # 使用uvicorn启动FastAPI服务
        subprocess.run([
            sys.executable, "-m", "uvicorn", 
            "main_whisper:app", 
            "--host", "0.0.0.0", 
            "--port", "8000",
            "--reload"  # 开发模式下自动重载
        ])
    except KeyboardInterrupt:
        print("服务已停止")
    except Exception as e:
        print(f"服务启动失败: {e}")

if __name__ == "__main__":
    # 安装依赖
    install_dependencies()
    
    # 等待短暂时间确保依赖安装完成
    time.sleep(1)
    
    # 启动服务
    start_server()